import React, { useEffect, useRef, useState } from "react";
import { Layout, Button, Input } from 'antd'
import ChatBox from "../components/ChatBox";
import { msgType } from "../types";
import { getRandomString } from "../utils/math";

const { Header, Content, Sider } = Layout;
const chatMap = new Map()

export default function ChatView() {
    const msgRef = useRef([])
    const [msgList, setMsgList] = useState([])
    const [chatId, setChatId] = useState(getRandomString())
    const [reply, setReply] = useState('')

    useEffect(() => {
        console.log(msgRef.current)
        setMsgList(msgRef.current)
    }, [msgRef.current.length])

    const addNewChat = () => {
        console.log('add chat')
        chatMap.set(chatId, msgList)
        const _chatId = getRandomString()
        console.log(_chatId, '_chatId')
        setMsgList([])
        setChatId(_chatId)
    }

    const changeChat = (e) => {
        const _chatId = e.target.value.toString()
        console.log(_chatId)
        if (!chatMap.has(_chatId)) {
            console.log('chatId invalid', _chatId);
            return;
        }
        chatMap.set(chatId, msgList)
        const _list = chatMap.get(_chatId)
        console.log(_list, 'list')
        setMsgList(_list)
        setChatId(_chatId)
    }

    const onSendMessage = (message) => {
        // 此处请求接口那到返回数据 setReply
        // todo 修改消息获取方式
        setReply(getRandomString())
        // setMsgList(message)
    }

    const onMessagesChange = (msg) => {
        console.log(msg)
        setMsgList(msg)
    }

    return <>
        <Input onChange={val => changeChat(val)}></Input>
        <Button onClick={addNewChat}>new Chat</Button>
        <ChatBox chatId={chatId} msgList={msgList} reply={reply} onSendMessage={onSendMessage} onMessagesChange={onMessagesChange} />
    </>
}